package com.huangliusong.order.controller;

import com.huangliusong.order.VO.ResultVO;
import com.huangliusong.order.VO.ResultVOUtil;
import com.huangliusong.order.converter.OrderForm2OrderDto;
import com.huangliusong.order.dto.OrderDTO;
import com.huangliusong.order.enums.ResultEnum;
import com.huangliusong.order.exception.OrderException;
import com.huangliusong.order.form.OrderForm;
import com.huangliusong.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * @author huangliusong
 * @since 2018/10/20
 * {@link }
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    @PostMapping("/create")
    public ResultVO<Map<String, String>> create(@Valid OrderForm orderForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.error("创建订单参数不正确 orderForm={}", orderForm);
            throw new OrderException(1, bindingResult.getFieldError().getDefaultMessage());

        }
        //orderForm转成orderdto
        OrderDTO orderDTO = OrderForm2OrderDto.convert(orderForm);
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailsList())) {
            log.error("创建订单 购物车信息为空");
            throw new OrderException(ResultEnum.CART_EMPTY);
        }

        OrderDTO result = orderService.create(orderDTO);
        Map<String, String> map = new HashMap<>();
        map.put("orderId", result.getOrderId());

        return ResultVOUtil.success(map);
    }
}
